node.js child | 您所在的位置:网站首页 › nodejs执行linux命令 输出转字符串 › node.js child |
问题
使用node的child_process的exec方法执行cmd命令的时候,执行结果带有中文的部分乱码 解决原先写法是: var child_process = require('child_process'); child_process.exec('ipconfig', { encoding:“utf-8”}, function(err, stdout, stderr){ console.log(stdout, stderr) });需要纠正下,改成如下写法即可: var child_process = require('child_process'); var iconv = require('iconv-lite'); var encoding = 'cp936'; var binaryEncoding = 'binary'; child_process.exec('ipconfig', { encoding: binaryEncoding }, function(err, stdout, stderr){ console.log(iconv.decode(new Buffer(stdout, binaryEncoding), encoding), iconv.decode(new Buffer(stderr, binaryEncoding), encoding)); }); 分析简体中文windows命令行,都使用的是CP936(近似于gb2312)编码,nodejs以utf8识别是会出问题。 可以这样处理: 先用binary来存储输出的文本,再用iconv来以cp936解析。 |
CopyRight 2018-2019 实验室设备网 版权所有 |